package com.dmxtechnologies.community.ejb.interfaces.impl;

import java.util.logging.Logger;

import javax.annotation.Resource;
import javax.ejb.Schedule;
import javax.ejb.Singleton;
import javax.ejb.Startup;
import javax.resource.ResourceException;

import com.dmxtechnologies.community.ejb.interfaces.JWHIndexTimeBroadcastRemote;
import com.dmxtechnologies.community.rar.api.CMSBaseRequest;
import com.dmxtechnologies.community.rar.api.CMSBaseResponse;
import com.dmxtechnologies.community.rar.api.CMSConnection;
import com.dmxtechnologies.community.rar.api.CMSConnectionFactory;
import com.dmxtechnologies.community.rar.api.CMSProcessingException;

/**
 * Session Bean implementation class JWHIndexTimeBroadcast
 */
@Singleton
@Startup
public class JWHIndexTimeBroadcast implements JWHIndexTimeBroadcastRemote {
	private static final Logger log = Logger.getLogger("JWHIndexTimeBroadcast");
	@Resource(lookup = "java:global/env/eis/DMXCMSConnectionFactory")
	private CMSConnectionFactory connectionFactory;

	private CMSBaseResponse baseResponse = null;
    /**
     * Default constructor. 
     */
    public JWHIndexTimeBroadcast() {
        // TODO Auto-generated constructor stub
    }
    
    @Schedule(minute = "*/55", hour = "*", persistent = false)
	public void timer() throws Exception {
    	//每次更新只更新第一页
		sendRequest(1); 
	}

	private void sendRequest(int pageNumber) throws CMSProcessingException,
			Exception, ResourceException {
		// L_229781_00406001_json_229781_1
		CMSBaseRequest request = new CMSBaseRequest();
		request.setCommunity("229781");
		request.setPreColumns("00406001");
		request.setTemplateExample("json");
		request.setNextColumns("229781");
		request.setPagination(pageNumber);
		log.info("[ResourceAccessBean] Getting connection from the RA");
		try (CMSConnection connection = connectionFactory.getConnection()) {
			baseResponse = connection.getListRequestToCMS(request);
			log.info("invoke success");
		}
	}

	@Override
	public CMSBaseResponse getJWHIndexList() throws Exception {
		if(baseResponse == null){
			this.timer();
		}
		
		return baseResponse;
	}
 
	@Override
	public CMSBaseResponse getJWHIndexListInPageNum(int pageNumber) throws Exception{
		sendRequest(pageNumber);
		return baseResponse;
	}

}
